/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.database;

import br.com.models.Days;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Valdigleis
 */
public class DaoDays{
    
    private String sql;
    
    private Connection connection;
    
    public DaoDays(){
        this.connection = Derby.getConnection();
    }
    
    public boolean save(Days day){
        try{
            sql = "INSERT INTO SAD.DAYS" +
                " (name)" + " values (?)";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, day.getName());
            stmt.execute();
            stmt.close();
            connection.close();
            return true;
        }catch(SQLException e){
            System.out.println(e.getMessage());
        }
        return false;
    }
    
    /**
     * Método que encontra um dia especifico na base de dados.
     * @param idDay
     * @return 
     */
    public ArrayList<Days> seacherDays(ArrayList<Integer> ids){
        try{
            ArrayList<Days> days = new ArrayList<Days>();
            sql = "SELECT * FROM SAD.DAYS WHERE id=?";
            PreparedStatement stmt = connection.prepareStatement(sql);
            for(int i = 0; i < ids.size(); i++){
                Days day = new Days();
                stmt.setInt(1, ids.get(i).intValue());
                ResultSet rs = stmt.executeQuery();
                rs.next(); 
                day.setId(rs.getInt("id"));
                day.setName(rs.getString("name"));
                days.add(day);
            }
            stmt.close();
            return days;
        }catch(SQLException e){
            System.out.println(e.getMessage());
            return null;
        }
    }
    
    public Days getDay(Integer ids){
        try{
            sql = "SELECT * FROM SAD.DAYS WHERE id=?";
            PreparedStatement stmt = connection.prepareStatement(sql);
            Days day = new Days();
            stmt.setInt(1, ids);
            ResultSet rs = stmt.executeQuery();
            rs.next(); 
            day.setId(rs.getInt("id"));
            day.setName(rs.getString("name"));
            stmt.close();
            closeConnection();
            return day;
        }catch(SQLException e){
            System.out.println(e.getMessage());
            return null;
        }
    }
    
    /**
     * Método que finaliza a conexão com a base de dados.
     */
    public void closeConnection(){
        try{
            this.connection.close();
        }catch(SQLException e){
            System.err.println("Erro tentar fechar a conexão da classe Days!");
            System.out.println(e.getMessage());
        }
    }
}
